package com.example.firstspringboot.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(urlPatterns = {"/*"})
public class MyFilter implements Filter {
    private List<String> IPList = new ArrayList<>(); // 黑名单
    private List<String> Words = new ArrayList<>(); // 敏感词汇

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { // 过滤器初始化
        Words.add("TMD"); // 敏感词汇
        Words.add("NMD");
    }

    public boolean check(String word) {
        for (String s : Words) {
            if (word.contains(s)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String ip = servletRequest.getRemoteAddr(); // 获得客户端 ip 地址
        String word = servletRequest.getParameter("word"); // 获得url请求中的word参数
        servletResponse.setContentType("text/html;charset=utf-8");
        if (IPList.contains(ip)) {
            servletResponse.getWriter().println("你已被列入黑名单!");
        } else if (word != null && check(word.toUpperCase())) { // 敏感词汇判断
            servletResponse.getWriter().println("提交数据有敏感词汇! 你已被列入黑名单!");
            IPList.add(ip);
        } else {
            filterChain.doFilter(servletRequest, servletResponse); // 其他情况直接放行
        }
    }
}
